<template>
  <!-- 直播带货榜 -->
  <div id="bring_goods01" style="min-height:100vh;position: relative;">
    <div class="updateTimewl">
      数据更新时间：
      <span style="color:#888">{{ time }}</span>
    </div>
    <div class="btn_group">
      <button @click="generatorImage">
        <span></span>分享
      </button>
      <button @click="export_data">
        <span></span>导出
      </button>
    </div>
    <ul
      class="fixedThead"
      ref="fixedThead"
      :class="{ isShow: isFixed }"
      :style="showLeft == true ? 'left:222px' : 'left:98px'"
      v-if="table_data01.length"
    >
      <li tc>排名</li>
      <li>达人</li>
      <li>直播间</li>
      <li tc>直播时长</li>
      <li tc>直播销量</li>
      <li
        tc
        @click="sort_fun(false, 3)"
        style="cursor: pointer;"
        v-if="sort == 'desc' && order_by != 'live_sales'"
      >
        直播销售额
        <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'live_sales'" />
        <img src="@/assets/meng/no_down_up.png" v-else />
      </li>
      <li tc v-if="sort == 'desc' && order_by == 'live_sales'">
        直播销售额
        <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'live_sales'" />
        <img src="@/assets/meng/no_down_up.png" v-else />
      </li>
      <li
        tc
        style="  cursor: pointer;"
        @click="sort_fun(false, 4)"
        v-if="sort == 'desc' && order_by != 'score'"
      >
        带货热度
        <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'score'" />
        <img src="@/assets/meng/no_down_up.png" v-else />
      </li>
      <li tc v-if="sort == 'desc' && order_by == 'score'">
        带货热度
        <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'score'" />
        <img src="@/assets/meng/no_down_up.png" v-else />
      </li>
      <li tc>上榜时长</li>
      <li tc>操作</li>
    </ul>
    <table class="table" ref="tableEl">
      <thead>
        <tr :class="{ is_fixed: isFixed }" ref="th_tr_El">
          <th>排名</th>
          <th>达人</th>
          <th>直播间</th>
          <th>直播时长</th>
          <th>直播销量</th>
          <th
            @click="sort_fun(false, 3)"
            style="cursor: pointer;"
            v-if="sort == 'desc' && order_by != 'live_sales'"
          >
            直播销售额
            <img
              src="@/assets/meng/down_up.png"
              v-if="sort == 'desc' && order_by == 'live_sales'"
            />
            <img src="@/assets/meng/no_down_up.png" v-else />
          </th>
          <th v-if="sort == 'desc' && order_by == 'live_sales'">
            直播销售额
            <img
              src="@/assets/meng/down_up.png"
              v-if="sort == 'desc' && order_by == 'live_sales'"
            />
            <img src="@/assets/meng/no_down_up.png" v-else />
          </th>
          <th
            style="  cursor: pointer;"
            @click="sort_fun(false, 4)"
            v-if="sort == 'desc' && order_by != 'score'"
          >
            带货热度
            <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'score'" />
            <img src="@/assets/meng/no_down_up.png" v-else />
          </th>
          <th v-if="sort == 'desc' && order_by == 'score'">
            带货热度
            <img src="@/assets/meng/down_up.png" v-if="sort == 'desc' && order_by == 'score'" />
            <img src="@/assets/meng/no_down_up.png" v-else />
          </th>
          <th>上榜时长</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in table_data01" :key="'table' + index" :id="!index ? 'tr1' : ''">
          <td class="td td_01">{{ 30*(page-1)+index+1 }}</td>

          <td class="td td_03">
            <div @click="goTalentDetails(item.author_id)">
              <img v-lazy="item.logo" v-errorImg:talent />
              <section>
                <div>
                  <img v-if="item.is_shop == 1" src="../../../assets/meng/search_result01.png" />
                  <span class="dot">{{ item.nickname }}</span>
                </div>
                <div>粉丝数：{{ format_num(item.total_fans) }}</div>
              </section>
            </div>
          </td>
          <td class="td td_02">
            <div>
              <div>
                <img
                  v-lazy="item.room_logo"
                  class="pointer"
                  @click="go_to_page(item.room_id)"
                  v-errorImg:live
                />
                <div>
                  <p class="livingGif">
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                  </p>
                </div>
              </div>
              <section>
                <div>
                  <img v-if="item.is_shop" src="../../../assets/meng/pop01.png" />
                  <img v-if="item.is_red" src="../../../assets/meng/pop02.png" />
                  <span class="dot pointer" @click="go_to_page(item.room_id)">{{ item.room_title }}</span>
                </div>
                <div></div>
                <p></p>
              </section>
            </div>
          </td>
          <td class="td td_05">
            <div>
              {{
              format_time(
              new Date(item.end_time.replace(/-/g, "/")).getTime() -
              new Date(item.begin_time.replace(/-/g, "/")).getTime()
              )
              }}
            </div>
          </td>
          <td class="td td_04">
            <div>{{ format_num(item.live_volume) }}</div>
          </td>
          <td class="td td_05">
            <div>{{ format_num(item.live_sales) }}</div>
          </td>
          <td class="td td_06">
            <div>{{ format_num(item.score) }}</div>
          </td>
          <td class="td td_06">
            <div>{{ format_timehm(item.line_time * 1000) }}</div>
          </td>
          <td class="td td_07">
            <button @click="go_to_page(item.room_id)">数据大屏</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="paginationBox pageBox" v-if="table_data01 && table_data01.length">
      <el-pagination
        class="pageBox"
        background
        layout="prev, pager, next, jumper"
        :total="count"
        :page-size="size"
        :current-page="page"
        @current-change="currentChange"
      ></el-pagination>
    </div>
    <p class="permissions" v-if="!permissions">
      当前为免费版会员，仅可查看100个结果，立即
      <span @click="$router.push('/talent_main/buy')">升级会员版本</span>，可查看更多数据
    </p>

    <!-- <p class="nothing" v-show="!loading && table_data01.length != 0">我是有底线的～</p> -->
    <div
      v-loading="loading"
      v-if="loading"
      class="loading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
    ></div>

    <div class="empty" v-show="!loading && table_data01.length == 0">
      <img src="@/assets/liu/zw.png" />
      <p>暂无数据</p>
    </div>
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
import superman from '@/assets/img/superman.png';
import liveVideo from '@/assets/img/live-video.png';
export default {
  name: 'bring_goods01',
  components: {},
  data() {
    return {
      superman: superman,
      liveVideo: liveVideo,
      permissions: 1,
      loading: true,
      table_data01: [],
      isFixed: false,
      showLeft: true,
      time: '',
      sort: 'desc', //   表格头部排序
      order_by: 'live_sales', //   表格头部排序
      updateTime: '',
      updateTime: new Date(),
      page: 1,
      size: 30,
      count: 0,
      result: 0
    };
  },
  computed: {},
  created() {
    let that = this;
    that.updateTime = that.timestamp(that.updateTime.getTime() / 1000, 'Y-M-D h:m:s');
    this.get_data();
  },
  watch: {
    '$store.state.left_nav_flag'(old, newOld) {
      this.showLeft = newOld;
      if ((newOld = false)) {
        this.setTBBar();
      } else {
        this.setTBBar();
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.initHeight);
    window.addEventListener('resize', () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar();
    });
  },
  methods: {
    currentChange(page) {
      this.table_data01 = [];
      this.page = page;
      this.table_data01 = this.result.slice((page - 1) * this.size, this.size * page);
      window.scrollTo(0,0);
    },

    //   表格头部排序
    sort_fun(parm01, parm02) {
      this.table_data01 = [];
      if (parm01) {
        this.sort = 'asc';
      } else {
        this.sort = 'desc';
      }
      switch (parm02) {
        case 3:
          this.order_by = 'live_sales';
          break;
        case 4:
          this.order_by = 'score';
          break;
      }
      this.get_data();
    },
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false;
      let nodes = pNode.childNodes;
      let newList = [];
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node);
        }
      }
      return newList;
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl;
        let ulEl = this.$refs.fixedThead;
        let tr1 = document.querySelector('#tr1');
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1);
          let liEls = this.getChilds(ulEl);
          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + 'px';
          }
        }
      });
    },

    get_data() {
      this.loading = true;
      let that = this;
      this.$axios({
        method: 'get',
        url: '/api/live/GetLiveProHourRank',
        params: {
          orderby: this.order_by,
          sort: this.sort
        }
      })
        .then(response => {
          this.loading = false;
          if (response.data.code == 1003) {
            this.permissions = 0;
          }
          if (response.data.code == 0) {
            this.result = response.data.data;
            this.count = this.result.length;
            this.table_data01 = this.result.slice(
              (this.page - 1) * this.size,
              this.size * this.page
            );
            this.time = this.table_data01[0].create_time;
            // 2021-06-18 16:36:42
            this.time = this.time.slice(0, -3);
            this.setTBBar();
          }
        })
        .catch(error => {
          this.loading = false;
          console.log(error);
        });
    },
    go_to_page(id) {
      let router = this.$router.resolve({
        path: `/live/${id}`
      });
      window.open(router.href, '_blank');
    },
    // go_to_page01(id) {
    //   let router = this.$router.resolve({
    //     path: `/talent_main/tdetails/${id}/${0}`
    //   });
    //   window.open(router.href, '_blank');
    // },
    goTalentDetails(id) {
      let router = this.$router.resolve({
        path: `/talent_main/tdetails/${id}/${0}`
      });
      window.open(router.href, '_blank');
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.isFixed = scrollTop > 120 ? true : false;
    },
    // 导出分享
    generatorImage() {
      //分享截图
      if (this.table_data01.length) {
        var that = this;
        const loading = this.$loading({
          lock: true,
          text: '导出中...',
          spinner: 'el-icon-loading',
          customClass: 'customClass'
        });
        var shareContent;
        shareContent = this.$refs.tableEl; //需要截图的包裹的（原生的）DOM 对象
        var width = shareContent.offsetWidth; //获取dom 宽度
        var height = shareContent.offsetHeight; //获取dom 高度
        var canvas = document.createElement('canvas'); //创建一个canvas节点
        //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
        var scale = 1;
        canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
        canvas.height = height * scale * scale; //定义canvas高度 *缩放
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        canvas.getContext('2d').scale(scale, scale); //获取context,设置scale
        var opts = {
          dpi: window.devicePixelRatio,
          scale: scale, // 添加的scale 参数
          useCORS: true,
          canvas: canvas, //自定义 canvas
          logging: true //日志开关
        };
        html2canvas(shareContent, opts).then(canvas => {
          let str;
          str = `《直播带货榜-${this.timestamp(new Date().getTime() / 1000, 'Y-M-D')}》.png`;
          canvas.toBlob(
            function (blob) {
              const eleLink = document.createElement('a');
              eleLink.download = str;
              eleLink.style.display = 'none';
              // 字符内容转变成blob地址
              eleLink.href = URL.createObjectURL(blob);
              // 触发点击
              document.body.appendChild(eleLink);
              eleLink.click();
              // 然后移除
              document.body.removeChild(eleLink);
            },
            'image/png',
            1
          );
          loading.close();
        });
      }
    },
    export_data() {
      if (this.table_data01.length) {
        let that = this;
        // let str = `排名,直播间,达人,粉丝数,关联话题,人气数值,上榜时长\n`;
        let str = `排名,达人,直播间,直播时长,直播销量,直播销售额,上榜时长\n`;
        for (let i = 0; i < that.table_data01.length; i++) {
          str += `${i + 1},${that.table_data01[i].nickname.replace(
            /"/g,
            '""'
          )}\",\"${that.table_data01[i].room_title.replace(/"/g, '""')}\",${that.format_time(
            new Date(that.table_data01[i].end_time.replace(/-/g, '/')).getTime() -
              new Date(that.table_data01[i].begin_time.replace(/-/g, '/')).getTime()
          )},\"
        ${that.format_num(that.table_data01[i].live_volume)}\",${that.format_num(
            that.table_data01[i].live_sales
          )},${that.format_timehm(that.table_data01[i].line_time * 1000)}\n`;
        }
        // for (let i = 0; i < that.table_data01.length; i++) {
        //   str += `${i + 1},\"${that.table_data01[i].room_title.replace(
        //     /"/g,
        //     '""'
        //   )}\",${that.table_data01[i].nickname.replace(/"/g, '""')}\",${that.format_num(
        //     that.table_data01[i].total_fans
        //   )},\"
        // ${that.table_data01[i].topic.replace(/"/g, '""')}\",${that.format_num(
        //     that.table_data01[i].score
        //   )},${that.format_time(that.table_data01[i].line_time * 1000)}\n`;
        // }

        var blob = new Blob([str], { type: 'text/plain;charset=utf-8' }); //解决中文乱码问题
        blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
        let object_url = window.URL.createObjectURL(blob);
        var link = document.createElement('a');
        link.href = object_url;
        let str_name = `《直播带货榜-${that.timestamp(new Date().getTime() / 1000, 'Y-M-D')}》.csv`;
        link.download = str_name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.initHeight);
  }
};
</script>
<style scoped lang="less">
.updateTimewl {
  position: absolute;
  top: -34px;
  right: 20px;
  font-size: 14px;
  color: #888;
  letter-spacing: 0 !important;
}
// 导出 + 分享
.btn_group {
  text-align: right;
  margin-bottom: 20px;
  justify-content: right;
  button {
    width: 70px;
    height: 32px;
    border-radius: 4px;
    border: solid 1px #e5e5e5;
    font-size: 14px;
    // line-height: 30px;
    box-sizing: border-box;
    color: #555;
    text-align: center;
  }
  button:nth-of-type(2) {
    color: #67ac5b;
    border: 1px solid #67ac5b;
  }

  > button:nth-child(1) {
    margin-right: 10px;
    span {
      display: inline-block;
      width: 14px;
      height: 14px;
      background: url('../../../assets/zhao/fenx.png') no-repeat;
      background-size: 100% 100%;
      margin-right: 4px;
      position: relative;
      top: 2px;
    }
  }
  > button:nth-child(2) {
    span {
      display: inline-block;
      width: 14px;
      height: 14px;
      background: url('../../../assets/zhao/daoc.png') no-repeat;
      background-size: 100% 100%;
      margin-right: 4px;
      position: relative;
      top: 2px;
    }
  }
  button:nth-of-type(1):hover {
    color: #777;
    span {
      background: url('../../../assets/zhao/fenx_h.png') no-repeat;
      background-size: 100% 100%;
    }
  }
  button:nth-of-type(2):hover {
    color: #80be76;
    border-color: #80be76;
    span {
      background: url('../../../assets/zhao/daoc_h.png') no-repeat;
      background-size: 100% 100%;
    }
  }
}
//
.table {
  width: 100%;
  position: relative;

  thead {
    position: relative;
    tr {
      > th:nth-child(1) {
        width: 6%;
      }
      > th:nth-child(2) {
        width: 330px;
        text-align: left;
      }
      > th:nth-child(3) {
        width: 262px;
        text-align: left;
        padding-left: 5px;
      }
    }
    img {
      width: 5px;
      height: 10px;
    }
  }
  tbody {
    overflow-y: auto;
    tr {
      height: 78px;
    }
    .td_07 {
      text-align: center;
      button {
        width: 88px;
        height: 32px;
        border: 1px solid #fd7f2c;
        border-radius: 4px;
        font-size: 14px;
        font-weight: normal;
        font-stretch: normal;

        letter-spacing: 0px;
        color: #fd7f2c;
        text-align: center;
        background: transparent;
      }
      button:hover {
        border: 1px solid #ff924b;
        color: #ff924b;
      }
    }

    .td_01,
    .td_05,
    .td_06 {
      font-family: DINAlternate-Bold;
      font-size: 15px;
      text-align: center;
    }
    .td_04 {
      font-size: 15px;
    }
    .td_03 {
      cursor: pointer;
      overflow: hidden;
      > div {
        section {
          > div:first-child {
            display: flex;
            align-items: center;
            > span {
              display: block;
              max-width: 200px;
              width: fit-content;
              word-break: break-all;
              font-size: 14px;
              color: #222222;
              font-weight: 600;
              margin-bottom: 5px;
            }
            > span:hover {
              color: #fd7f2c;
            }
            img {
              width: 16px;
              height: 16px;
              margin-right: 4px;
              margin-top: -4px;
            }
          }
          > div:last-child {
            width: 100%;
            word-break: break-all;
            font-size: 14px;
            color: #888;
          }
        }
        > img {
          border-radius: 50%;
          box-sizing: border-box;
          width: 50px;
          margin-right: 12px;
          border: 1px solid #e5e5e5;
        }
      }
    }
    .td_03 {
      > div {
        justify-content: flex-start !important;
      }
    }
    .td_02 {
      > div {
        justify-content: flex-start !important;
        > div:nth-child(1) {
          position: relative;
          > div {
            position: absolute;
            bottom: 0px;
            right: 13px;
            width: 18px;
            height: 18px;
            background-image: linear-gradient(90deg, #ff295d 1%, #fa4fa2 100%),
              linear-gradient(#ffffff, #ffffff);
            background-blend-mode: normal, normal;
            border-radius: 6px 0 4px 0px;
            font-size: 12px;
            color: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            padding-left: 2px;
          }
          > img {
            width: 50px;
            height: 50px;
            border-radius: 6px;
            margin-right: 12px;
            border: 1px solid #e5e5e5;
          }
        }
        section {
          > div:nth-child(1) {
            display: flex;
            align-items: center;
            > span {
              display: block;
              max-width: 164px;
              width: fit-content;
              word-break: break-all;
              font-size: 14px;
              color: #222222;
              font-weight: 600;
              margin-bottom: 5px;
            }
            > span:hover {
              color: #fd7f2c;
            }
            img {
              height: 16px;
              margin-right: 4px;
              margin-top: -3px;
            }
          }
          > div:nth-child(2) {
            width: 100%;
            word-break: break-all;
            font-size: 14px;
            color: #555555;
          }
          > p:nth-child(3) {
            button {
              padding: 3px 10px;
              border-radius: 21px;
              border: solid 1px #fd7f2c;
              background-color: #f5f9ff;
              font-size: 14px;
              color: #fd7f2c;
              margin-right: 10px;
              margin-top: 7px;
            }
          }
        }
      }
    }
    .td {
      > div {
        height: 70px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
.fixedThead {
  display: none;
  position: fixed;
  top: 60px;
  left: 200px;

  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #555;
  background-color: #f5f9ff;
  height: 48px;
  line-height: 48px;
  overflow: hidden;
  z-index: 99;
  font-size: 0;

  li {
    box-sizing: border-box;
    display: inline-block;
    font-size: 14px;
  }
  &.isShow {
    display: block;
  }
  img {
    width: 5px;
    height: 10px;
    vertical-align: 0px;
  }
}
[tc] {
  text-align: center;
}
[tl] {
  text-align: left;
}
[tr] {
  text-align: right;
}
#bring_goods01 {
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 20px;
}
.paginationBox {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 30px 0 40px;
  .el-pagination {
    // margin-top: 20px;
    // position: absolute;
    // left: 50%;
    // transform: translateX(-50%);
  }
}
</style>
